<?php


namespace app\shop\controller;


use app\BaseController;
use app\shop\common\consts\Consts;
use app\shop\common\lists\ListsSearchTrait;
use app\shop\common\lists\ListsSortTrait;
use app\shop\controller\interfaces\ModelInterface;
use app\shop\controller\interfaces\SearchInterface;
use app\shop\model\user\UserModel;
use ReflectionClass;
use think\App;
use think\facade\Validate;
use think\Model;

abstract class BaseAdminController extends BaseController implements SearchInterface, ModelInterface
{
    use ListsSearchTrait;
    use ListsSortTrait;
    protected $model;
    protected $search;
    protected $sort;

    protected $page = 1;
    protected $limit = 10;

    protected $field = '*';
    protected $withModel;
    protected $namespace = 'app\\shop\\controller\\admin';
    protected $returnType = false;
    protected $validate;
    protected $validateScene;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->params = $this->request->param();
        $this->page = $app->request->param('page', 1);
        $this->limit = $app->request->param('limit', 10);

        $namespace = $this->namespace;
        $controller = $this->request->controller();
        $len = strpos($controller, '.');
        $controller = $len ? substr($controller, $len + 1) : $controller;

        $childClass = $namespace . '\\' . $controller . 'Controller';
        $action = $this->request->action();

        $childMethod = new \ReflectionMethod($childClass, $action);
        try {
            $parentMethod = new \ReflectionMethod(__CLASS__, $action);
            $this->returnType = $childMethod->getDeclaringClass()->getName() !== $parentMethod->getDeclaringClass()->getName();
        } catch (\Exception $exception) {

        }
    }

    public function initWhere()
    {
        return $this->searchWhere = $this->createWhere($this->search);
    }


    public function initSort()
    {
        return $this->createSort($this->sort, $this->request->param('order_by', 'create_time'), $this->request->param('sort', 'desc'));
    }


    public function getModel(): Model
    {
        return $this->model;
    }

    /**
     * 获取列表
     * @return \think\Paginator|\think\response\Json
     */
    public function getList()
    {
        try {
            $this->initWhere();
            $this->initSort();
//            var_dump($this->searchWhere);
            $list = $this->getModel()
                ->field($this->field)
                ->when($this->withModel, function ($query) {
                    $query->with($this->withModel);
                })
                ->where($this->searchWhere)
                ->order($this->orderBy, $this->sort)
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page]);
            if (!$this->returnType) {
                return $this->success($list->toArray());
            } else {
                return $list;
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 添加，修改
     * @param array $data
     * @return \think\response\Json
     */
    public function save(array $data = [])
    {
        try {
            $param = $this->request->param('', '', 'trim');

            if ($this->validate) {
                if ($this->scene) {
                    Validate($this->validate)->scene($this->scene)->check($data);
                } else {
                    Validate($this->validate)->check($data);
                }
            }

            $pk = $this->getModel()->getPk();

            $data = $data ? $data : $param;

            if (isset($data[$pk]) && $data[$pk]) {
                unset($data['create_time']);
                $model = $this->getModel()->where($pk, $data[$pk])->find();
                $model->save($data);
            } else {
                $model = $this->getModel();
                $model->save($data);
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 删除
     * @return \think\response\Json
     */
    public function del()
    {
        try {
            $id = $this->request->param('id', 0);

            $pk = $this->getModel()->getPk();

            $model = $this->getModel()->where($pk, $id)->find();

            $model->delete();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 修改状态
     * @return \think\response\Json
     */
    public function status()
    {
        try {
            $id = $this->request->param('id', 0);
            $field = $this->request->param('field', 'is_del', 'trim');
            $status = $this->request->param('status', 0);

            $pk = $this->getModel()->getPk();

            $model = $this->getModel()->where($pk, $id)->find();
            $model->$field = $status;
            $model->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 获取数组
     * @return array|\think\response\Json
     */
    public function getArr()
    {
        try {
            $list = $this->getModel()->select()->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 删除文件
     * \think\response\Json
     */
    public function removeFile()
    {
        try {
            $filePath = $this->request->param('unlink_file_name');
            if ($filePath) {
                unlink(public_path() . $filePath);
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}